package com.nidu.demo.tenant.ability;

import com.alibaba.cola.exception.BizException;
import com.nidu.demo.common.exception.ErrorCodeConstants;
import com.nidu.demo.tenant.gateway.TenantGateway;
import com.nidu.demo.tenant.model.Tenant;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
public class TenantDomainService {

    private final TenantGateway gateway;

    public void validateDuplicate(String name, Long excludeId) {
        // 检查名称是否重复
        Tenant tenant = gateway.getByName(name);
        if (tenant != null) {
            if(excludeId == null){
                throw new BizException(ErrorCodeConstants.TENANT_NAME_DUPLICATE.getCode(),
                        ErrorCodeConstants.TENANT_NAME_DUPLICATE.getMessage());
            } else if(!excludeId.equals(tenant.getId())) {
                throw new BizException(ErrorCodeConstants.TENANT_NAME_DUPLICATE.getCode(),
                        ErrorCodeConstants.TENANT_NAME_DUPLICATE.getMessage());
            }
        }
    }

    public void validateTenant(Long id) {
        if(id != null){
            Tenant tenant = gateway.getById(id);
            if (tenant == null) {
                throw new BizException(ErrorCodeConstants.TENANT_NOT_FOUND.getCode(),
                        ErrorCodeConstants.TENANT_NOT_FOUND.getMessage());
            }
            tenant.isDisable();
            tenant.isDeleted();
            tenant.isExpired();
        }
    }
}